package com.yunkuhui.www.demo.exceptionhandler;

import org.apache.tomcat.util.http.fileupload.FileUploadBase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import java.util.HashMap;
import java.util.Map;

/**
 * @ RestControllerAdvice 的范围有：
 * ①basePackages：应用在xx包
 * ②basePackageClasses：应用在xx类
 * ③assignableTypes：应用在加了@Controller的类
 * ④annotations：应用在带有xx注解的类或者方法
 */
@RestControllerAdvice(basePackages = {"com.yunkuhui.www.demo.controller"})
@AutoConfigureBefore(SystemExceptionHandler.class)
public class ControllerExceptionHandler {

	private final static Logger logger = LoggerFactory.getLogger(ControllerExceptionHandler.class);

	@ExceptionHandler(value = {ArithmeticException.class})
	public Map<String, String> zeroValueExceptionHandler(Exception e) {
		logger.debug("除数为0" ,e);
		System.out.println("ArithmeticException");
		Map<String, String> errorMap = new HashMap<>();
		errorMap.put("resultCode", "01");
		errorMap.put("errorCode", "BE0004");
		errorMap.put("errorMessage", "除以0");
		return errorMap;
	}

	@ExceptionHandler(value = {IllegalStateException.class})
	public Object subscriptCrossoverExceptionHandler(Exception e) {
		System.out.println("IllegalStateException");
		e.printStackTrace();
//		Map<String, String> errorMap = new HashMap<>();
//		errorMap.put("resultCode", "01");
//		errorMap.put("errorCode", "BE0004");
//		errorMap.put("errorMessage", "下标越界");
		return "下标越界";
	}

	@ExceptionHandler(value = {MaxUploadSizeExceededException.class})
	public Object maxUploadSizeExceededExceptionHandler(Exception e) {
		e.printStackTrace();
		return "文件大小超出限制";
	}
}
